package com.example.tabbar.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.CompoundButton
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.tabbar.adapter.SamplingDataAdapter
import com.example.tabbar.databinding.FragmentSamplingDataBinding
import com.junray.common.ktx.CustomGlobalScope
import com.junray.common.ktx.io
import com.junray.usermangement.room.bean.SamplingData
import com.junray.usermangement.room.entity.Location
import com.junray.usermangement.room.entity.Measurement
import com.junray.usermangement.room.entity.RecordMeasurement
import com.junray.usermangement.utils.TimeUtils
import com.junray.usermangement.viewModel.MeasurementViewModel


class SamplingDataFragment : Fragment() {
    private var binding: FragmentSamplingDataBinding? = null
    private var recyclerView: RecyclerView? = null
    private var adapter: SamplingDataAdapter? = null
    private var multiple: CheckBox? = null  // 多选

    private var meaViewModel : MeasurementViewModel? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentSamplingDataBinding.inflate(inflater, container, false)
        return binding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        meaViewModel = ViewModelProvider(this)[(MeasurementViewModel::class.java)]

        initView()

        binding?.add?.setOnClickListener {
            insertData()
        }
        binding?.recipePrint?.setOnClickListener {
//            meaViewModel?.getMeasurementByUserAndLocation(1,1)?.observe(viewLifecycleOwner) { samplingData ->
//                Log.d("SamplingData", "查看关联记录数据: $samplingData")
//            }
            // 模拟插入位置研发测试
            val location = listOf(Location("", "群组1"))
            location.forEach {
                meaViewModel?.insertLocation(it)
            }
        }

        // 调用recyclerview列表的监听器
        adapterListenerClick()
    }

    private fun adapterListenerClick() {
        adapter?.setOnMeasurementClickListener { samplingData, position ->
            // 更新适配器的测量数据列表
            meaViewModel!!.getMeasurementByUserAndLocation(
                samplingData.userId,
                samplingData.locationId
            ).observe(viewLifecycleOwner) { measurements ->
                if (measurements.isNotEmpty()) {
                    adapter?.updateMeasurementsAtPosition(position, measurements)
                }
            }
        }

        // 在 onViewCreated 方法中添加
        adapter?.setOnItemClickListener { item ->
            // 跳转到详情页面
            (parentFragment as? SearchFragment)?.navigateToDetail(item.userId,item.locationId,"",item.locationName )
        }

        adapter?.setOnItemLocationListener { _ ->
            (parentFragment as? SearchFragment)?.navigateToDetail(null,null,"DETAILS_DATA")
        }


    }

    private fun insertData() {
        CustomGlobalScope.io {
            val measurement =
                Measurement(
                    userId = 2,
                    locationId = 2,
                    startTime = TimeUtils.currentTime,
                    endTime = TimeUtils.getNextMinute(),
                    result = true,
                    flowRate = 28.3,
                    value03 = 1234,
                    value05 = 555,
                    samplingLoc = "Loc5",
                    air = "CO"
                )
            insertMeasurementAndRecord(measurement)
        }
    }
    private fun insertMeasurementAndRecord(measurement: Measurement) {
        CustomGlobalScope.io {
            // 插入测量数据
            meaViewModel?.insertMeasurement(measurement)

            val recordData = meaViewModel?.getRecordMeasurement(measurement.userId, measurement.locationId)

            if(recordData != null) {
                // 更新现有记录的结束时间
                val updatedRecord = recordData.copy(
                    endTime = measurement.endTime
                )
                meaViewModel?.updateRecordMeasurement(updatedRecord)
            } else {
                // 创建对应的记录数据
                val recordMeasurement = RecordMeasurement(
                    userId = measurement.userId,
                    locationId = measurement.locationId,
                    startTime = measurement.startTime,
                    endTime = measurement.endTime,
                    flowRate = measurement.flowRate,
                    air = measurement.air
                )
                // 插入记录数据2
                meaViewModel?.insertRecordMeasurement(recordMeasurement)
                Log.d("SamplingDataFragment", "记录数据插入成功")
            }
        }
    }

    private fun initView() {
        recyclerView = binding?.samplingList
        adapter = SamplingDataAdapter()
        recyclerView?.adapter = adapter
        recyclerView?.layoutManager = LinearLayoutManager(requireContext())
        multiple = binding?.multiple


        meaViewModel?.getSamplingData()?.observe(viewLifecycleOwner) { item: List<SamplingData>? ->
            if (!item.isNullOrEmpty()) {
                adapter?.setItems(item)
            }
        }

        // 创建一个统一的监听器处理两个 CheckBox
        val checkBoxListener: (CompoundButton, Boolean) -> Unit = { _, isChecked ->
            adapter?.selectAll(isChecked)
        }

        adapter?.setOnItemSelectClickListener { isSelect ->

            // 临时移除监听器避免循环调用
            multiple?.setOnCheckedChangeListener(null)

            // 同步多选Checkbox的状态
            multiple?.isChecked = isSelect

            // 重新设置监听器
            multiple?.setOnCheckedChangeListener(checkBoxListener)
        }

        multiple?.setOnCheckedChangeListener(checkBoxListener)
    }

    @SuppressLint("StaticFieldLeak")
    companion object {

        @Volatile
        private var instance: SamplingDataFragment? = null

        @JvmStatic
        fun newInstance(): SamplingDataFragment =
            instance ?: synchronized(this) {
                instance ?: SamplingDataFragment().apply {
                    arguments = Bundle().apply {}
                }.also { instance = it }
            }
    }
}